<template>
  <list-group :dataList.sync="tableData"
              :loading="loading"
              prop="borrower"
              listHeight="calc(100% - 48px)"
              :defaultSize="defaultListSize"
              @saveHandler="saveHandler"
              @delHandler="delHandler"
              @addHandler="addHandler"
              @page-handler="getTableData"
              @change="getTableData()">
    <template v-slot:toolBar>
      <input type="checkbox" v-model="unpaidOnly" @change="getTableData()">{{$t('borrow.unpaidOnly')}}
    </template>
    <template v-slot:left="{ item, index }">
      <el-form
        :model="item"
        class="l-h-1-6em"
        label-width="60px"
        :rules="rules"
        :ref="'form1'+index"
      >
        <span v-show="!item.inEdit">
          <div
            :title="item.borrower"
            class="text-overflow"
          >
            {{ item.borrower }}
          </div>
        </span>
        <el-form-item
          prop="borrower"
          v-show="item.inEdit === true"
          :rules="rules.borrower"
          class="margin-left-xs-60px"
        >
          <el-autocomplete
            class="w-130px"
            v-model="item.borrower"
            :fetch-suggestions="getNameTextList"
            :placeholder="$t('common.pleaseInput')"
            :trigger-on-focus="true"
            :clearable="true"
            @input="validateProp('borrower', index)"
          >
          <template slot-scope="{ item }">
            <div class="autocompelete-item-container">
              <div class="autocompelete-label" :title="item.value">{{item.value}}</div>
              <i class="iconfont icon-close autocompelete-close" @click.stop="deleteNameTextHandler(item.id)" />
            </div>
          </template>
          </el-autocomplete>
        </el-form-item>
      </el-form>
    </template>
    <template v-slot:middle="{item,index}">
      <el-form :model="item"
               class="l-h-1-6em"
               label-width="60px"
               :rules="rules"
               :ref="'form2'+index">
        <span class="text-info"
              v-show="item.inEdit!==true">{{$t('common.amount')}}</span>
        <span v-show="item.inEdit!==true">{{parseFloat(item.amount).toFixed(2)}}</span>
        <el-form-item prop="amount"
                      :rules="rules.amount"
                      :label="$t('common.amount')"
                      v-show="item.inEdit===true">
          <el-input v-model="item.amount"
                    class="w-130px"
                    :precision="2"
                    :step="0.1"></el-input>
        </el-form-item>
        <div v-show="item.inEdit!==true">
          <span class="text-info">{{dateFormat(item.date)}}</span>
          <span class="text-info">{{item.actualRepaymentDate?$t('borrow.repaid'):$t('borrow.unpaid')}}</span>
        </div>
        <el-form-item prop="date"
                      :rules="rules.date"
                      :label="$t('borrow.borrow')"
                      v-show="item.inEdit===true">
          <el-date-picker v-model="item.date"
                          class="w-130px"
                          :picker-options="pickerOptions"
                          v-show="item.inEdit"
                          type="date"></el-date-picker>
        </el-form-item>
        <el-form-item prop="actualRepaymentDate"
                      :rules="rules.actualRepaymentDate"
                      :label="$t('borrow.repay')"
                      v-show="item.inEdit===true">
          <el-date-picker v-model="item.actualRepaymentDate"
                          class="w-130px"
                          :picker-options="pickerOptions"
                          v-show="item.inEdit"
                          type="date"></el-date-picker>
        </el-form-item>
      </el-form>
    </template>
  </list-group>
</template>
<script>
import { queryBorrowingList, upsertBorrowing, deleteBorrowing, upsertNameText, queryNameTextList, deleteNameText } from '@/assets/api'
import { formatDate, greaterThanEqualsNow } from '@/assets/utils/commonUtil'
import ListGroup from '@/components/common/listGroup/Index.vue'
import validationUtil from '@/assets/utils/validationUtil'
const BLUR = 'blur'
export default {
  data () {
    return {
      unpaidOnly: true,
      tableData: {},
      loading: false,
      pickerOptions: { disabledDate: greaterThanEqualsNow },
      defaultListSize: 10,
      autoCompeleteQueryStr: '',
      autoCompeleteCB: {},
      rules: {
        borrower: [
          { required: true, message: this.$t('validationMessage.inputRequired'), trigger: BLUR }
        ],
        amount: [
          { required: true, message: this.$t('validationMessage.inputRequired'), trigger: BLUR },
          {
            validator: validationUtil.isFloat,
            trigger: BLUR
          }
        ],
        date: [
          { required: true, message: this.$t('validationMessage.inputRequired'), trigger: BLUR }
        ]
      }
    }
  },
  components: { ListGroup },
  mounted () { this.getTableData() },
  methods: {
    getTableData (limit = this.defaultListSize, offset = 0) {
      if (limit !== this.defaultListSize) { this.defaultListSize = limit }
      this.loading = true
      if (this.tableData.list) { this.tableData.list.splice(0, this.tableData.list.length) }
      queryBorrowingList({ unpaidOnly: this.unpaidOnly, limit: limit, offset: offset }).then(res => {
        this.tableData = res.data
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    delHandler (index) {
      this.loading = true
      deleteBorrowing({ id: this.tableData.list[index].id }).then(res => {
        this.$message({ type: 'success', message: this.$t('common.deleted') })
        this.getTableData()
        this.$emit('updated')
      })
    },
    saveHandler (index) {
      this.$refs['form1' + index].validate((valid1) => {
        this.$refs['form2' + index].validate((valid) => {
          if (valid) {
            this.loading = true
            upsertBorrowing(this.tableData.list[index]).then(res => {
              this.getTableData()
              this.$emit('updated')
            }, () => {
              this.getTableData()
            })
            upsertNameText({ text: this.tableData.list[index].borrower, type: 'borrower' })
          }
        })
      })
    },
    addHandler () {
      this.$set(this.tableData.list[0], 'date', this.dateMonth)
    },
    dateFormat (date) {
      return formatDate(date, 'yyyy-MM-dd')
    },
    getNameTextList (queryStr, cb) {
      if (queryStr !== null) {
        this.autoCompeleteQueryStr = queryStr
      }
      if (cb) {
        this.autoCompeleteCB = cb
      }
      this.autoCompeleteQueryStr = this.autoCompeleteQueryStr || ''
      queryNameTextList({ type: 'borrower', searchText: this.autoCompeleteQueryStr }).then(res => {
        const result = res.data.map(item => { item.value = item.text; return item })
        this.autoCompeleteCB(result)
      }, () => { })
    },
    deleteNameTextHandler (id) {
      deleteNameText({ id: id }).then(res => {
        this.getNameTextList(null, null)
        this.$message({
          type: 'success',
          message: this.$t('common.deleted')
        })
      })
    },
    validateProp (prop, index) {
      this.$refs['form1' + index].validateField(prop)
    }
  }
}
</script>
